<template>
	<view>
		<view v-if="showTable">
			<scroll-view class="scroll-view" scroll-x="true">
				<view class="pagination">
					<view v-if="sheets.length > 1" class="tab" :class="index == sheetIndex ?'tab-selected':'' "
						v-for="(item,index) in sheets" :key="index" @click="selectSheet(index)">
						{{item.name}}
					</view>
				</view>
			</scroll-view>

			<!-- 表结构 -->
			<uni-table :loading="loading" ref="table" border stripe emptyText="暂无更多数据">
				<!-- 表头行 -->
				<uni-tr>
					<uni-th align="center" v-for="(item,index) in tableTitles" :key="index"
						width="150px">{{item}}</uni-th>
				</uni-tr>
				<!-- 表格数据行 -->
				<uni-tr v-for="(item,index) in tableList" :key="index">
					<uni-td align="center" v-for="(items,i) in item" :key="i">
						<input :value="items" type="text" :class="{'disabled': isDisabled(i)}"
							@input="handleInputChange(index, i, $event)" />
					</uni-td>
				</uni-tr>
			</uni-table>
		</view>
	</view>
</template>
<script>
	// import * as XLSX from 'xlsx';
	import * as XLSX from 'xlsx';
	export default {
		props: {
			// 文件大小上限 M
			size: {
				type: Number,
				default: 10
			}
		},
		data() {
			return {
				loading: false,
				// 本地文件路径
				filePath: '',
				// 文件名
				fileName: '',
				// table表状态
				showTable: false,
				// 表数据
				workbookData: {},
				// sheet列表
				sheets: [],
				// 选中索引
				sheetIndex: 0,
				// 表格表头
				tableTitles: [],
				// 表格数据
				tableList: [],
				// app 文件对象
				// appFile: null,
				// 文件上限 为了正常显示只能传一个文件
				count: 1,
				month: new Date().getMonth() + 1
			}
		},
		computed: {

		},
		methods: {
			isDisabled(index) {

				return index > 3 && index - 3 <= new Date().getDate() && new Date().getMonth() + 1 == this.month;
			},
			// 修改xls内容
			handleInputChange(rowIndex, colIndex, event) {
				// 更新 tableList 中对应的数据
				this.tableList[rowIndex][colIndex] = event.target.value;
				console.log(this.tableList);
				// this.$emit('scheduleList', this.tableList)
			},
			// 选择文件
			chooseFile() {
				
				this.loading = true
				
				this.tableList = []
				let that = this;
				
				// 如果是微信小程序，从聊天记录选择文件 wx.qy.chooseMessageFile
				wx.qy.chooseMessageFile({
					count: 1,
					type: "file",
					extension: ['xls', 'xlsx'],
					success(res) {
						that.filePath = res.tempFiles[0].path
						that.fileName = res.tempFiles[0].name.split('.')[0]
						// 获取文件信息流
						var FileSystemManager = wx.getFileSystemManager();
						FileSystemManager.readFile({
							filePath: res.tempFiles[0].path,
							encoding: 'base64',
							success(data) {
								
								// 解析excel信息流
								const workbook = XLSX.read(data.data, {
									type: "base64",
									cellText: false,
									cellDates: true,
								});
								
								uni.showToast({
									title: "请在表格数据显示完成后点击上传按钮",
									icon: 'loading',
									duration: 3000
								});
								
								that.workbookData = workbook;
								that.sheets = workbook.Workbook.Sheets;

								that.selectSheet(0)
							},
							fail(err) {
								console.log('fail', err)
							}
						})
					}
				})
				// #ifdef H5
				wx.chooseFile({
					count: 1, //默认100
					extension: ['.xls', '.xlsx'],
					success: function(res) {
						this.filePath = res.tempFiles[0].path
						this.fileName = res.tempFiles[0].name.split('.')[0]
						// 获取文件流
						const fileReader = new FileReader();
						fileReader.onload = ev => {
							try {
								const data = ev.target.result;

								const workbook = XLSX.read(data, {
									type: "binary",
									cellText: false,
									cellDates: true,
								});
								that.workbookData = workbook;
								that.sheets = workbook.Workbook.Sheets;
								that.selectSheet(0)
							} catch (e) {
								console.error("上传失败", e)
							}
						}
						const blob = new Blob([res.tempFiles[0]]);
						fileReader.readAsBinaryString(blob);

					}
				});
				// #endif
				// #ifdef APP
				if (this._size >= this.count) {
					console.log(`只允许上传${this.count}个文件`)
					return;
				}
				// #endif
			},
			// 查询sheet数据
			// -----------------------------------------

			selectSheet(i) {
				if (!this.showTable) {
					this.showTable = true;
				}
				this.sheetIndex = i;
				let key = this.sheets[i].name;
				//循环读取每个文件
				const header = XLSX.utils.sheet_to_json(this.workbookData.Sheets[key], {
					header: 1,
					blankRows: true, // 保留空行
					defval: '休' // 设置空单元格的默认值为空字符串
				});
				
				// 过滤掉整行都是 '休' 的行
				const filteredHeaders = header.filter(row => 
				  !row.every(cell => cell === '休')
				);
				
				console.log(filteredHeaders);
				
				
				
				// console.log("表头数据",this.tableTitles);
				const date = this.$parent.date


				let hasEmptyFields = false;
				// 过滤掉包含 "休" 的行，并处理剩余行
				const filteredHeader = filteredHeaders.slice(2).filter(item => {
					// 检查前三个元素是否包含 "休"
					const containsRest = item.slice(0, 3).includes("休");

					const allEmpty = item.slice(0, 3).every(i => i === "休"); // 检查前四个元素是否全部为 "休"
					console.log(item.slice(0,3));
					if (containsRest && !allEmpty) {
						hasEmptyFields = true; // 设置标志为 true
						wx.showModal({
							title: '提示',
							content: '上传班表有空姓名，空工号，请检查后在上传',
							showCancel: false,
							success: function(res) {
								if (res.confirm) {
									console.log('用户点击确定');
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							}
						});
					}

					return !containsRest; // 返回 false 时删除该行
				});


				// 遍历过滤后的行，处理最后一个元素
				filteredHeader.forEach(item => {
					if (date.length <= item.length) {
						item.pop(); // 删除最后一个元素
					}
				});

				if (hasEmptyFields) {
					console.warn('检测到空字段，停止进一步处理。');
					// 这里可以添加逻辑，比如返回或退出函数
				} else {
					wx.hideLoading()
					// 继续处理正常的数据
					// 更新 header 或其他操作
					// header.splice(2, header.length - 2, ...filteredHeader);
					// // this.tableList = header.slice(2)
					// this.$emit('scheduleList', header.slice(2))
					
					filteredHeaders.splice(2, filteredHeaders.length - 2, ...filteredHeader);
					this.tableList = filteredHeaders.slice(2)
					this.$emit('scheduleList', filteredHeaders.slice(2))
				}
				// 如果需要将过滤后的结果赋值回 header.slice(2)，可以这样做
				// header.splice(2, header.length - 2, ...filteredHeader);

			},

			// -----------------------------------------------------------------------

			// header.slice(2).forEach((item, index) => {
			// 	item.forEach((i, x) => {
			// 		if (x <= 3) {
			// 			console.log(x);
			// 			console.log(i);
			// 			if (i == "休") {
			// 				// item.pop()
			// 				item.splice(index, 1);
			// 			}
			// 		}
			// 	})
			// 	if (date.length <= item.length) {
			// 		item.pop();
			// 	}
			// })
			// // this.tableTitles = header[0];
			// console.log("1111",this.tableTitles);
			// this.tableList = header.slice(1)
			// console.log(header.slice(1));
			// console.log(this.tableList);
		}
	}
</script>
<style lang="scss">
	.scroll-view {
		width: 100%;
		white-space: nowrap;

		.pagination {
			margin: 0 auto;
			padding: 0 auto;

			.tab {
				width: 120upx;
				display: inline-block;
				margin: 0 10rpx;
				padding: 20upx 0;
				margin-top: 10upx;
				text-align: center;
				border: 1px solid #007aff;

				&-selected {
					background-color: #007aff;
					color: #ffffff;
				}
			}
		}
	}

	.disabled {
		pointer-events: none;
		opacity: 0.5;
	}
</style>